package com.ouyy.volunteerservice.volunteer.controller;

import cn.hutool.core.lang.UUID;
import com.ouyy.volunteerservice.volunteer.domain.po.Volunteer;
import com.ouyy.volunteerservice.volunteer.domain.po.VolunteerRegistration;
import com.ouyy.volunteerservice.volunteer.mapper.VolunteersMapper;
import com.ouyy.volunteerservice.volunteer.service.VolunteerRegistrationService;
import com.ouyy.volunteerservice.volunteer.service.VolunteerService;
import com.ouyy.volunteerservice.volunteer.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@RestController
@RequestMapping("/volunteers")
public class VolunteerController {

    @Autowired
    private VolunteerService volunteerService;

    @Autowired
    private VolunteersMapper volunteersMapper;


    @Autowired
    private VolunteerRegistrationService registrationService;

    // 用户注册
    @PostMapping("/register")
    public ResponseResult register(@RequestBody Volunteer volunteer) {
        int volunteerId = Math.abs(UUID.randomUUID().toString().hashCode()); // 取 UUID 哈希值的绝对值
        volunteer.setVolunteerId(String.valueOf(volunteerId));
        // 验证用户名是否已存在
        if (volunteerService.lambdaQuery().eq(Volunteer::getName, volunteer.getName()).count() > 0) {
            return new ResponseResult(false, "用户名已存在");
        }

        // 验证手机号是否符合格式
        String phonePattern = "^[0-9]{11}$";
        Pattern pattern = Pattern.compile(phonePattern);
        Matcher matcher = pattern.matcher(volunteer.getPhoneNumber());
        if (!matcher.matches()) {
            return new ResponseResult(false, "手机号格式不正确");
        }

        // 验证邮箱是否符合格式
        String emailPattern = "^[A-Za-z0-9+_.-]+@(.+)$";
        pattern = Pattern.compile(emailPattern);
        matcher = pattern.matcher(volunteer.getEmail());
        if (!matcher.matches()) {
            return new ResponseResult(false, "邮箱格式不正确");
        }

        // 密码和确认密码一致性检查
        if (!volunteer.getPassword().equals(volunteer.getPassword())) {
            return new ResponseResult(false, "密码和确认密码不一致");
        }

        // 默认设置其他字段（如注册日期等）
        volunteer.setRegistrationDate(LocalDateTime.now());

        // 保存志愿者信息
        boolean result = volunteerService.save(volunteer);
        if (result) {
            return new ResponseResult(true, "注册成功");
        } else {
            return new ResponseResult(false, "注册失败，请稍后重试");
        }
    }

    // 用户登录
    @PostMapping("/login")
    public ResponseResult login(@RequestBody Volunteer volunteer) {
        // 查找用户是否存在
        Volunteer existingVolunteer = volunteerService.lambdaQuery()
                .eq(Volunteer::getName, volunteer.getName())
                .eq(Volunteer::getPassword, volunteer.getPassword()) // 密码加密后验证
                .one();

        if (existingVolunteer == null) {
            return new ResponseResult(false, "用户名或密码错误");
        }
        if (existingVolunteer.getIsAdmin() == 0){
            return new ResponseResult(true, "管理员登录成功", existingVolunteer);
        }

        return new ResponseResult(true, "登录成功", existingVolunteer);
    }

    // 获取所有志愿者
    @GetMapping("/list")
    public ResponseResult getAllVolunteers() {
        List<Volunteer> volunteers = volunteerService.list();
        return new ResponseResult(true, "查询成功", volunteers);
    }

    // 根据 ID 获取志愿者
    @GetMapping("/{id}")
    public ResponseResult getVolunteerById(@PathVariable Integer id) {
        Volunteer volunteer = volunteerService.getById(id);
        if (volunteer == null) {
            return new ResponseResult(false, "志愿者不存在");
        }
        return new ResponseResult(true, "查询成功", volunteer);
    }

    @GetMapping("/searchByOrganizationId")
    public List<Volunteer> getVolunteersByOrganizationId(@RequestParam String organizationId) {
        return volunteerService.getByOrganizationId(organizationId);
    }

    // 新增志愿者
    @PostMapping("/add")
    public ResponseResult addVolunteer(@RequestBody Volunteer volunteer) {
        boolean result = volunteerService.save(volunteer);
        if (result) {
            return new ResponseResult(true, "新增成功");
        } else {
            return new ResponseResult(false, "新增失败");
        }
    }

    /**
     * 根据activate获取志愿者列表
     * @param volunteer
     * @return
     */
    @GetMapping("/searchByActivate")
    public List<Volunteer> getVolunteersByActivate(@RequestParam String activate) {
        List<Volunteer> volunteers = new ArrayList<>();
        List<VolunteerRegistration> list = registrationService.lambdaQuery().eq(VolunteerRegistration::getActivityId, activate).list();
        for (VolunteerRegistration registration : list) {
            Volunteer volunteer = volunteerService.getById(registration.getVolunteerId());
            volunteers.add(volunteer);
        }
        return volunteers;
    }



    // 更新志愿者信息
    @PutMapping("/update")
    public ResponseResult updateVolunteer(@RequestBody Volunteer volunteer) {
        boolean result = volunteerService.updateById(volunteer);
        if (result) {
            return new ResponseResult(true, "更新成功");
        } else {
            return new ResponseResult(false, "更新失败");
        }
    }



    // 删除志愿者
    @DeleteMapping("/delete/{id}")
    public ResponseResult deleteVolunteer(@PathVariable Integer id) {
        boolean result = volunteerService.removeById(id);
        if (result) {
            return new ResponseResult(true, "删除成功");
        } else {
            return new ResponseResult(false, "删除失败");
        }
    }


    @PutMapping("/updateSelective")
    public ResponseResult updateSelective(@RequestBody Volunteer volunteer) {
        // 获取原始数据
        Volunteer existingVolunteer = volunteerService.getById(volunteer.getVolunteerId());
        if (existingVolunteer == null) {
            return new ResponseResult(false, "志愿者不存在");
        }
        log.error("获取的数据:"+existingVolunteer);
        log.error("更新的数据:"+volunteer);
        // 逐个检查并更新非空字段
        if (volunteer.getName() != null) {
            existingVolunteer.setName(volunteer.getName());
        }
        if (volunteer.getAvatar() != null) {
            existingVolunteer.setAvatar(volunteer.getAvatar());
        }
        if (volunteer.getTotalServiceHours() != null) {
            existingVolunteer.setTotalServiceHours(volunteer.getTotalServiceHours());
        }
        if (volunteer.getSystemRank() != null) {
            existingVolunteer.setSystemRank(volunteer.getSystemRank());
        }
        if (volunteer.getOrganizationIds() != null) {
            existingVolunteer.setOrganizationIds(volunteer.getOrganizationIds());
        }
        if (volunteer.getJoinTime() != null) {
            existingVolunteer.setJoinTime(volunteer.getJoinTime());
        }
        if (volunteer.getLeaveTime() != null) {
            existingVolunteer.setLeaveTime(volunteer.getLeaveTime());
        }
        if (volunteer.getNumberOfActivities() != null) {
            existingVolunteer.setNumberOfActivities(volunteer.getNumberOfActivities());
        }
        if (volunteer.getPoliticalAffiliation() != null) {
            existingVolunteer.setPoliticalAffiliation(volunteer.getPoliticalAffiliation());
        }
        if (volunteer.getEmail() != null) {
            existingVolunteer.setEmail(volunteer.getEmail());
        }
        if (volunteer.getPhoneNumber() != null) {
            existingVolunteer.setPhoneNumber(volunteer.getPhoneNumber());
        }
        if (volunteer.getWechat() != null) {
            existingVolunteer.setWechat(volunteer.getWechat());
        }
        if (volunteer.getQq() != null) {
            existingVolunteer.setQq(volunteer.getQq());
        }
        if (volunteer.getAddress() != null) {
            existingVolunteer.setAddress(volunteer.getAddress());
        }
        if (volunteer.getServiceArea() != null) {
            existingVolunteer.setServiceArea(volunteer.getServiceArea());
        }
        if (volunteer.getAvailableServiceTime() != null) {
            existingVolunteer.setAvailableServiceTime(volunteer.getAvailableServiceTime());
        }
        if (volunteer.getInterestedServiceCategories() != null) {
            existingVolunteer.setInterestedServiceCategories(volunteer.getInterestedServiceCategories());
        }
        if (volunteer.getActivityInvitationPermission() != null) {
            existingVolunteer.setActivityInvitationPermission(volunteer.getActivityInvitationPermission());
        }
        if (volunteer.getOrganizationInvitationPermission() != null) {
            existingVolunteer.setOrganizationInvitationPermission(volunteer.getOrganizationInvitationPermission());
        }
        if (volunteer.getPassword() != null) {
            existingVolunteer.setPassword(volunteer.getPassword());
        }
        if (volunteer.getIsAdmin() != null) {
            existingVolunteer.setIsAdmin(volunteer.getIsAdmin());
        }

        // 执行更新操作
        boolean result = volunteerService.updateById(existingVolunteer);
        return result ? new ResponseResult(true, "更新成功") : new ResponseResult(false, "更新失败");
    }


    @PutMapping("/joinTeam")
    public ResponseResult joinTeam(@RequestBody Volunteer volunteer) {
        String newOrganizationId = volunteer.getOrganizationIds(); // 获取前端传来的组织ID
        log.error("newOrganizationId: " + newOrganizationId);

        if (newOrganizationId == null || newOrganizationId.trim().isEmpty()) {
            return new ResponseResult(false, "组织ID不能为空");
        }

        // 查询数据库，获取当前 volunteer 的信息
        Volunteer existingVolunteer = volunteerService.getById(volunteer.getVolunteerId());
        if (existingVolunteer == null) {
            return new ResponseResult(false, "志愿者不存在");
        }

        String currentOrganizationIds = existingVolunteer.getOrganizationIds();
        log.error("currentOrganizationIds: " + currentOrganizationIds);

        // 如果当前组织ID列表不为空，并且已经加入了该组织，则返回提示
        if (currentOrganizationIds != null && !currentOrganizationIds.trim().isEmpty()) {
            List<String> orgList = Arrays.asList(currentOrganizationIds.split(","));
            if (orgList.contains(newOrganizationId)) {
                return new ResponseResult(false, "已加入该团队");
            }
            currentOrganizationIds += "," + newOrganizationId; // 拼接新ID
        } else {
            currentOrganizationIds = newOrganizationId; // 直接赋值
        }

        volunteer.setOrganizationIds(currentOrganizationIds);

        // 更新数据库
        boolean result = volunteerService.updateById(volunteer);

        return result ? new ResponseResult(true, "加入团队成功") : new ResponseResult(false, "加入团队失败");
    }


    @PutMapping("/leaveTeam")
    public ResponseResult leaveTeam(@RequestBody Volunteer volunteer) {
        String removeOrganizationId = volunteer.getOrganizationIds(); // 获取要退出的组织ID
        log.error("removeOrganizationId: " + removeOrganizationId);

        if (removeOrganizationId == null || removeOrganizationId.trim().isEmpty()) {
            return new ResponseResult(false, "组织ID不能为空");
        }

        // 查询当前志愿者信息
        Volunteer existingVolunteer = volunteerService.getById(volunteer.getVolunteerId());
        if (existingVolunteer == null) {
            return new ResponseResult(false, "志愿者不存在");
        }

        String currentOrganizationIds = existingVolunteer.getOrganizationIds();
        log.error("currentOrganizationIds: " + currentOrganizationIds);

        if (currentOrganizationIds == null || currentOrganizationIds.trim().isEmpty()) {
            return new ResponseResult(false, "当前未加入任何团队");
        }

        // 解析组织ID列表
        List<String> orgList = new ArrayList<>(Arrays.asList(currentOrganizationIds.split(",")));
        log.error("orgList: " + orgList);
        if (!orgList.contains(removeOrganizationId)) {
            return new ResponseResult(false, "未加入该团队，无法退出");
        }

        // 移除指定的组织ID
        orgList.remove(removeOrganizationId);
        log.error("removeorgList: " + orgList);
        // 处理更新后的组织ID字段
        String updatedOrganizationIds = orgList.isEmpty() ? "" : String.join(",", orgList);
        log.error("updatedOrganizationIds: " + updatedOrganizationIds);
        existingVolunteer.setOrganizationIds(updatedOrganizationIds);

        // 更新数据库
        boolean result = volunteerService.updateById(existingVolunteer);

        return result ? new ResponseResult(true, "退出团队成功") : new ResponseResult(false, "退出团队失败");
    }


    /**
     * 计算志愿者数量
     * @return
     */
    @GetMapping("/count")
    public int countVolunteers() {
        return Math.toIntExact(volunteersMapper.selectCount(null)); // 计算志愿者总数
    }


    /**
     * 根据注册月份统计志愿者数量
     *
     * @return 按月份统计的志愿者人数
     */
    @GetMapping("/countByMonth")
    public List<Map<String, Object>> countVolunteersByMonth() {
        return volunteerService.getMonthlyVolunteerCounts();
    }

    @GetMapping("countByserviceTime")
    public List<Map<String, Object>> countVolunteersByServiceTime() {
        return volunteerService.getServiceTime();
    }
}
